package com.geekjob1120.geekjob1120pay.config;

import com.geekjob1120.geekjob1120pay.modle.PayWay;
import com.geekjob1120.geekjob1120pay.service.WeChatPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.util.ClassUtils;

@Slf4j
public class WeChatBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        log.info("微信bean工厂开始处理");
        boolean hasClass = ClassUtils.isPresent("com.geekjob1120.geekjob1120pay.service.WeChatPayService",
                WeChatBeanFactoryPostProcessor.class.getClassLoader());
        if (!hasClass){
            log.info("类路径未包含微信支付服务类");
            return;
        }
        if(beanFactory.containsBean(PayWay.WECHATPAY.name())){
            log.info("微信支付服务类已包含在bean工厂");
            return;
        }
        log.info("开始注册微信支付服务类");
        if (beanFactory instanceof BeanDefinitionRegistry){
            GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
            beanDefinition.setBeanClass(WeChatPayService.class);
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            registry.registerBeanDefinition(PayWay.WECHATPAY.name(),beanDefinition);
            log.info("已注册微信支付类");
        }
        else {
            beanFactory.registerSingleton(PayWay.WECHATPAY.name(),new WeChatPayService(true));
            log.info("已注册微信支付单例");
        }
    }
}
